package com.sky.business.sys.service.impl;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.business.sys.service.CmccApiService;
import com.sky.common.docker.exception.CmccApiCallException;
import com.sky.common.http.HttpDecorate;
import com.sky.common.http.HttpDecorateBuilder;
import com.sky.common.utils.StringUtils;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.SimpleTimeZone;

/**
 * cmcc接口服务实现类
 */
@Service
public class CmccApiServiceImpl implements CmccApiService {

    @Value("${cmcc.api.get-urls}")
    private String getUrls;

    public static ObjectMapper objectMapper = new ObjectMapper().setTimeZone(SimpleTimeZone.getTimeZone("GMT+8"));

    public static HttpDecorate httpDecorator = HttpDecorateBuilder.create().pool(10, 5).disableCookieManagement().build();

    @Override
    public String getPushStreamUrl(String stream, String hub) throws IOException {
        String url = getUrls.replace("{hub}",hub).replace("{stream}",stream);
        HttpUriRequest request = RequestBuilder.get().addHeader("Accept","*/*").addHeader("Content-Type","application/x-www-form-urlencoded").setUri(url).build();
        String json = httpDecorator.execute(request).result().string();
        JsonNode jsonNode = objectMapper.readTree(json);
        int code = jsonNode.get("code").asInt();
        if(code!=0){
            String msg = jsonNode.get("msg").asText();
            throw new CmccApiCallException(msg);
        }
        String pushUrl = jsonNode.get("data").get("push").get("rtmp").asText();
        if(StringUtils.isEmpty(pushUrl) || ! pushUrl.trim().toLowerCase().startsWith("rtmp")){
            throw new CmccApiCallException("无效的推流地址:"+pushUrl);
        }
        return pushUrl;
    }

}
